package com.mo.util;


import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Maps;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import java.util.Map;


public class SignUtil {

    /**
     * 把请求参数按字典顺序排序
     *
     * @param urlParam
     * @return
     */
    private static String concatParams(Map<String, String> urlParam) {
        Object[] key_arr = urlParam.keySet().toArray();
        Arrays.sort(key_arr);
        String str = "";
        for (Object key : key_arr) {
            String val = urlParam.get(key).toString();
            str += "&" + key + "=" + val;
        }
        return str.replaceFirst("&", "");
    }

    private static String byte2hex(byte[] b) {
        StringBuffer buf = new StringBuffer();
        int i;
        for (int offset = 0; offset < b.length; offset++) {
            i = b[offset];
            if (i < 0) i += 256;
            if (i < 16) buf.append("0");
            buf.append(Integer.toHexString(i));
        }
        return buf.toString();
    }

    public static String md5(String data) {
        MessageDigest md = null;
        try {
            md = MessageDigest.getInstance("MD5");
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
            return "";
        }
        return byte2hex(md.digest(data.getBytes()));
    }

    public static String sign(String pathUrl, Map<String, String> params, String secret) {
        String str = concatParams(params);
        str = pathUrl + "?" + str + "&" + secret;
//        System.out.println(str);
        return md5(str);
    }

    public static String mapToJson(Map<String, String> params) {
        JSONObject jsonObject = new JSONObject();
        jsonObject.putAll(params);
        return jsonObject.toString();
    }

    public static void sign(Map<String, String> params, String path) throws Exception {
        String appId = "6d5466889ea7c88cf1da2ddcb94b2a7c";
        String secret = "b42ed4b5647928e0183a29629c3b4783";
        String paramJson = mapToJson(params);
        String timestamp = String.valueOf(System.currentTimeMillis());
        String encrypt = AesUtil.encrypt(paramJson,secret);
        String encodeParam = CodeUtil.encode(encrypt);
        Map<String, String> encryptParams = Maps.newHashMap();
        encryptParams.put("appId", appId);
        encryptParams.put("data", encodeParam);
        encryptParams.put("timestamp", timestamp);
        String sign = sign(path, encryptParams, secret);
        System.out.println("timestamp: " + timestamp);
        System.out.println("data: " + encodeParam);
        System.out.println("sign: "+ sign);
    }


    public static void sign(String params, String path) throws Exception {
        String appId = "6d5466889ea7c88cf1da2ddcb94b2a7c";
        String secret = "b42ed4b5647928e0183a29629c3b4783";
//        String paramJson = mapToJson(params);
        String timestamp = String.valueOf(System.currentTimeMillis());
        String encrypt = AesUtil.encrypt(params,secret);
        String encodeParam = CodeUtil.encode(encrypt);
        Map<String, String> encryptParams = Maps.newHashMap();
        encryptParams.put("appId", appId);
        encryptParams.put("data", encodeParam);
        encryptParams.put("timestamp", timestamp);
        String sign = sign(path, encryptParams, secret);
        System.out.println("timestamp: " + timestamp);
        System.out.println("data: " + encodeParam);
        System.out.println("sign: "+ sign);
    }

    public static void decrypt(String data) throws Exception {
        String secret = "b42ed4b5647928e0183a29629c3b4783";
        String decodeData = CodeUtil.decode(data);
        String decrypt = AesUtil.decrypt(decodeData, secret);
        System.out.println(decrypt);
    }
   /* {
        "platform": 1,
            "filterWithCurrentUser": false,
            "pageNo": 1,
            "pageSize": 10000
    }*/
/*    public static void main(String[] args) throws Exception {
//        Map<String, String> params = Maps.newHashMap();
//        params.put("_t", "1693897438520");
//        sign(params, "/api/accountservice/mediaOpenAccountManage/getAdvertiserList");
//
//        decrypt("U2FsdGVkX19P9nEnVyWRpByOmhjurGQw3aPNnqnvBtwPSc3O85Bbxn0ZAzgi5Xf9x%2FlAqd020U1fMdBZ7QfqsfUNffid%2BsEi8Qf0mFJG5meKcvcfwkF%2FVWPFdPn2V7kMMWQsDErqzrioJTuk%2BcLwEYFPMAUvdzjdqiCv48OLhH7%2BSsafc5hCVtT6DQDePycY");

        sign("{\n" +
                "    \"platform\": 1,\n" +
                "    \"filterWithCurrentUser\": false,\n" +
                "    \"pageNo\": 1,\n" +
                "    \"pageSize\": 10000\n" +
                "}", "/api/oauthservice/media/pageUserInfo");
    }*/

    public static void main(String[] args) throws Exception {
//        Map<String, String> params = Maps.newHashMap();
//        params.put("_t", "1693897438520");
//        sign(params, "/api/accountservice/mediaOpenAccountManage/getAdvertiserList");
//
//        decrypt("U2FsdGVkX19P9nEnVyWRpByOmhjurGQw3aPNnqnvBtwPSc3O85Bbxn0ZAzgi5Xf9x%2FlAqd020U1fMdBZ7QfqsfUNffid%2BsEi8Qf0mFJG5meKcvcfwkF%2FVWPFdPn2V7kMMWQsDErqzrioJTuk%2BcLwEYFPMAUvdzjdqiCv48OLhH7%2BSsafc5hCVtT6DQDePycY");

        sign("{\"module\":\"media\"}", "/api/dashboard/custom-header");

       // sign("{\"platform\":57,\"pageNo\":2,\"pageSize\":\"1000\" }", "/api/customerservice/mediaAccountManage/pageSyncMediaAccount");
    }
}
